package com.example.mapdata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mapdata.dao.HotcityDao;
import com.example.mapdata.entity.Hotcity;
import com.example.mapdata.entity.Loginfo;
import com.example.mapdata.service.AreaService;
import com.example.mapdata.service.HotcityService;
import com.example.mapdata.service.LoginfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class HotcityServiceImpl implements HotcityService {

    @Autowired
    private HotcityDao hotcityDao;
    @Autowired
    private AreaService areaService;
    @Autowired
    private LoginfoService loginfoService;

    /**
     * 获取所有城市信息
     *
     * @return
     */
    @Override
    public List<Hotcity> getAllCity() {
        List<Hotcity> hotcities = hotcityDao.selectList(null);
        return hotcities;
    }

    /**
     * 根据城市编码获取城市信息
     *
     * @param code
     * @return
     */
    @Override
    public Hotcity getCityByCode(String code) {
        Hotcity cityInfoByCityCode = hotcityDao.getCityInfoByCityCode(code);
        return cityInfoByCityCode;
    }

    /**
     * 添加一条新的城市
     *
     * @param hotcity
     * @return
     */
    @Override
    public boolean addCityInfo(Hotcity hotcity) {
        int insert = hotcityDao.insert(hotcity);
        return insert > 0;
    }

    /**
     * 根据城市名称更新城市信息
     *
     * @param name
     * @return
     */
    @Override
    public boolean updateCityInfo(String name,Hotcity hotcity) {
        int i = hotcityDao.updateCityInfoByCityName(name, hotcity);
        return i > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 开启事务管理
    // rollbackFor = Exception.class => 只要出现异常就会执行 不管是 "运行时异常" 还是 ..
    public boolean deleteCityId(String cityId) {
        int res = 0;
        try {
            QueryWrapper qw = new QueryWrapper<>();
            qw.eq("city_id", cityId);

            int delete = hotcityDao.delete(qw);
            res = delete;
            // 运行时异常
            // int k = 1 / 0;
            log.info("出现bug");
            areaService.deleteAreaByCityId(cityId);

            return delete > 0;
        } finally {
            // 插入一条日志信息
            Loginfo loginfo = new Loginfo();
            loginfo.setCreateTime(new Date());
            loginfo.setDetail("删除了城市编号为: " + cityId + "的城市信息以及区县信息");
            loginfo.setStatus(res > 0 ? true : false);
            loginfoService.insertLoginfo(loginfo);
        }
    }
}
